package com.hub.nio.buf;


import java.nio.ByteBuffer;

/**
 * @ author 令狐冲
 * @ date & time 2025/2/5 11:29
 */
public class BufferExample {

    public static void main(String[] args) {
        byte[] resources = "hello".getBytes();
        // 初始化
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        System.out.println(byteBuffer.capacity());
        System.out.println(byteBuffer.position());
        System.out.println(byteBuffer.limit());
        // 写
        byteBuffer.put(resources);
        System.out.println(byteBuffer.capacity());
        System.out.println(byteBuffer.position());
        System.out.println(byteBuffer.limit());
        // 读
        // 不开读模式，读不到任何数据
        System.out.println(byteBuffer.get());
        System.out.println(byteBuffer.get());
        // 开起读模式才能读到数据
        byteBuffer.flip();
        System.out.println(byteBuffer.get());
        System.out.println(byteBuffer.get());

        // 读取全部
        System.out.println(new String(byteBuffer.array()));
    }
}
